//
//  BSKForgetPasswordViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/9.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <AVOSCloud/AVOSCloud.h>
#import <LeanCloudSocial/AVUser+SNS.h>
#import <KVNProgress/KVNProgress.h>

#import "BSKForgetPasswordViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKStringCheck.h"
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "UIViewController+BSKToast.h"
#import "IQKeyboardManager.h"

@interface BSKForgetPasswordViewController () <UITextFieldDelegate>
@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIView *emailView;
@property (strong, nonatomic) UIImageView *emailLogoImageView;
@property (strong, nonatomic) UITextField *emailTextField;
@property (strong, nonatomic) UIButton *sendButton;
@end

@implementation BSKForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.view.backgroundColor = [UIColor colorWithRed:0.9525 green:0.9525 blue:0.9525 alpha:1.0];
    [self initializeUserInterface];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.emailTextField becomeFirstResponder];
}
- (void)initializeUserInterface {
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *coverView = [[UIVisualEffectView alloc]initWithEffect:efect];
    UIImageView *imageView = [[UIImageView alloc] init];
    self.navView = [[UIView alloc] init];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleLabel = [[UILabel alloc] init];
    self.emailView = [[UIView alloc] init];
    self.emailLogoImageView = [[UIImageView alloc] init];
    self.emailTextField = [[UITextField alloc] init];
    self.sendButton = [[UIButton alloc] init];
    
    [self.view addSubview:imageView];
    [self.view addSubview:coverView];
    [self.view addSubview:self.navView];
    [self.navView addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.view addSubview:self.emailView];
    [self.emailView addSubview:self.emailLogoImageView];
    [self.emailView addSubview:self.emailTextField];
    [self.view addSubview:self.sendButton];
    
    coverView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    
    imageView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    imageView.image = [BSKTheme curentTheme].themeImage;
    
    self.navView.sd_layout.topEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(StatusBarHeight + NavigationBarHeight);
    //    self.navView.backgroundColor = [BSKTheme curentTheme].themeColor;
    //    self.navView.backgroundColor = [UIColor class]
    
    self.backButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .leftSpaceToView(self.navView, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleLabel.sd_layout.centerXIs(self.view.centerX)
    .centerYEqualToView(self.backButton);
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"找回密码";
    [self.titleLabel sizeToFit];
    
    self.emailView.sd_layout.centerXIs(self.view.centerX)
    .topSpaceToView(self.navView, 50)
    .leftSpaceToView(self.view, 30)
    .rightSpaceToView(self.view, 30)
    .heightIs(50);
    self.emailView.layer.cornerRadius = 10;
    self.emailView.layer.masksToBounds = YES;
    
    UIView *lineView = [[UIView alloc] init];
    [self.view addSubview:lineView];
    lineView.sd_layout.topSpaceToView(self.emailView, 0)
    .leftSpaceToView(self.view, 40)
    .rightSpaceToView(self.view, 40)
    .heightIs(1);
    lineView.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.emailLogoImageView.sd_layout.leftSpaceToView(self.emailView, 10)
    .topSpaceToView(self.emailView, 10)
    .heightIs(30)
    .widthIs(30);
    self.emailLogoImageView.image = [UIImage imageNamed:@"email"];
    self.emailLogoImageView.backgroundColor = [UIColor clearColor];
    
    self.emailTextField.sd_layout.topEqualToView(self.emailView)
    .leftSpaceToView(self.emailLogoImageView, 10)
    .rightEqualToView(self.emailView)
    .heightIs(50);
    self.emailTextField.delegate = self;
    self.emailTextField.borderStyle = UITextBorderStyleNone;
    self.emailTextField.placeholder = @"请输入邮箱";
    [self.emailTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.emailTextField.textColor = [UIColor whiteColor];
    self.emailTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    self.emailTextField.returnKeyType = UIReturnKeyDone;
    self.emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    
    self.sendButton.sd_layout.rightEqualToView(self.emailView)
    .topSpaceToView(self.emailView, 30)
    .widthRatioToView(self.emailView, 0.33)
    .heightIs(50);
    self.sendButton.backgroundColor = [BSKTheme curentTheme].themeColor;
    [self.sendButton setTitle:@"发送邮件" forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sendButton addTarget:self action:@selector(sendButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.sendButton.layer.cornerRadius = 5;
    self.sendButton.layer.masksToBounds = YES;
}
- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sendButtonAction:(UIButton *)sender {
    [self.view endEditing:YES];
    sender.enabled = NO;
    __weak typeof(self) weakSelf = self;
    if (_emailTextField.text.length == 0) {
        [self MakeToast:@"邮箱不能为空！" WithTime:1.5];
        sender.enabled = YES;
    } else if (![BSKStringCheck validateEmail:_emailTextField.text]) {
        [self MakeToast:@"邮箱格式不正确！" WithTime:1.5];
        sender.enabled = YES;
    } else {
        [KVNProgress show];
        [AVUser requestPasswordResetForEmailInBackground:_emailTextField.text block:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [KVNProgress dismiss];
                [weakSelf presentAlertWithMessage:@"验证邮件已发送至邮箱，请更改密码后登录!"];
            } else {
                [KVNProgress dismiss];
                NSString *emailStr = @"邮件发送失败，请检查邮件地址或网络连接！";
                if (error.code == 205) {
                    emailStr = @"该邮箱未被注册";
                }
                [weakSelf presentAlertWithMessage:emailStr];
            }
            sender.enabled = YES;
        }];
    }
}
- (void)presentAlertWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    if (textField.text.length == 0) {
        [self MakeToast:@"邮箱不能为空！" WithTime:1.5];
    } else if (![BSKStringCheck validateEmail:textField.text]) {
        [self MakeToast:@"邮箱格式不正确！" WithTime:1.5];
    } else {
        [self sendButtonAction:nil];
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
